package com.ghostbusters.fingertracker.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Serializer {

	/**
	 * Serializes the object , compresses it using gzip, and stores the file at "filename"
	 * @param o
	 * @param filename where to write out the object
	 */
	public static void GZIPserialize(Serializable o, String filename){
		try {
			FileOutputStream fileoutput = new FileOutputStream(filename);
			ObjectOutputStream out = new ObjectOutputStream(new GZIPOutputStream(fileoutput));
			out.writeObject(o);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Unzips a file, and returns the  object is represents
	 * @param t The type that the object should be. You can pass in any object of this type
	 * @param filename the filepath of the data
	 * @return
	 */
	public static <T> T GZIPdeserialize(T t, String filename){
		try {
			FileInputStream fileinput = new FileInputStream(filename);
			ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(fileinput));
			T newobj = (T) in.readObject();
			in.close();
			return newobj;
		} catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Serializes the object and stores the file at "filename"
	 * @param o
	 * @param filename where to write out the object
	 */
	public static void serialize(Serializable o, String filename){
		try {
			FileOutputStream fileoutput = new FileOutputStream(filename);
			ObjectOutputStream out = new ObjectOutputStream(fileoutput);
			out.writeObject(o);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Returns the desialized object o. 
	 * @param t The type that the object should be. You can pass in any object of this type
	 * @param filename the filepath of the data
	 * @return
	 */
	public static <T> T deserialize(T t, String filename){
		try {
			FileInputStream fileinput = new FileInputStream(filename);
			ObjectInputStream in = new ObjectInputStream(fileinput);
			T newobj = (T) in.readObject();
			in.close();
			return newobj;
		} catch (FileNotFoundException e){
			e.printStackTrace();
			return null;
		}catch (IOException e){
			return GZIPdeserialize(t, filename);
		}catch (ClassNotFoundException e){
			e.printStackTrace();
			return null;
		}
		
	}
	
}
